import { LOGIN_ROUTE_PATH } from '@/models/constant';
import { userLogoutUsingPost } from '@/services/novel-web/userController';
import { LoginOutlined, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { message } from 'antd';
import { createStyles } from 'antd-style';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';
import { MessageError, ToLogin } from '@/utils/commonUtils';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.nickname}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});


export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  
  // const { styles } = useStyles();

  const { initialState, setInitialState } = useModel('@@initialState');
  const [logined,setLogined] = useState(false);

  useEffect(()=>{
    if(initialState && initialState.currentUser ) {
      setLogined(true);
    }
    else {
      setLogined(false);
    }
    
  },[initialState?.currentUser])


  /**
   * 退出登录
   */
  const loginOut = async () => {
    try {
      const resp = await userLogoutUsingPost();
      if(resp.data) {
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        localStorage.removeItem('userToken');
        message.success("退出成功");
      }
    } catch(error: any) {
      MessageError(error);
    }
    
  };

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        loginOut();
       
        return;
      }
      else if(key === 'login') {
        // 保存当前路径，跳转到登录页面
        const curPath = window.location.pathname;
        history.push(`${LOGIN_ROUTE_PATH}?redirect=${encodeURIComponent(curPath)}`);
        return;
      }
      else if(key === 'home') {
        // if(logined) {
        //   history.push(`/user/home`);
        // }
        // else {
        //   ToLogin();
        // }
        history.push(`/user/home`);
        
      }
    },
    [setInitialState],
  );

  // 未登录时没有下拉状态
  // const loading = (
  //   <span className={styles.action}>
  //     <Spin
  //       size="small"
  //       style={{
  //         marginLeft: 8,
  //         marginRight: 8,
  //       }}
  //     />
  //   </span>
  // );
  // if (!initialState) {
  //   return loading;
  // }
  // const { currentUser } = initialState;
  // if (!currentUser || !currentUser.nickname) {
  //   return loading;
  // }

  const menuItems = [
    ...(menu
      ? [
          {
            key: 'home',
            icon: <UserOutlined />,
            label: '个人中心',
          },
          // {
          //   key: 'settings',
          //   icon: <SettingOutlined />,
          //   label: '个人设置',
          // },
          {
            type: 'divider' as const,
          },
        ]
      : []),
    (logined ? {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    } : {
      key: 'login',
      icon: <LoginOutlined />,
      label: '登录',
    }),
    
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {children}
    </HeaderDropdown>
  );
};
